const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();
const _ = cloud.database().command;

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const timestamp = event.timestamp;
  const user = await db.collection("user").where({
    openid:wxContext.OPENID,
  }).get()

  if(user.data.length == 0)
  {
    return {
      code:401,
      data:{},
      msg:"have not login"
   }
  }
  
  if(user.data[0].status != 0)
  {
    return {
      code:401,
		 data:{},
		 msg:"no privilege"
    }
  }

  let gt = timestamp - 21600000
  console.log(gt)
  const result = await db.collection("QRcode").where({
    timestamp:_.gt(gt)
  }).orderBy("timestamp","asc").limit(21).get()
  
  console.log(result)
  if(result.data.length == 0)
  {
    return {
      code:404,
      data:{},
      msg:"empty result"
    }
  }
  return {
    code:200,
    data:result.data[0],
    msg:"success"
  } 
};
